<?php

declare(strict_types=1);

namespace App\Amqp\Consumer;

use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use Hyperf\Amqp\Result;
use PhpAmqpLib\Message\AMQPMessage;
use Hyperf\Amqp\Message\Type;
use Service\Code\Normal;
use Service\SearchService\SearchService;
use Service\MonitorService\MonitorService;

/**
 * qos (prefetch_size,prefetch_count,global)
 * @Consumer(exchange="document_qqc_qqccommodity", routingKey="document_qqc_qqccommodity", queue="document_qqc_qqccommodity", nums=1)
 */
class QqcCommodityElasticSearchMessageConsumer extends ConsumerMessage
{
    protected $type = Type::DIRECT;//直连模式
    protected $qos  = [
        'prefetch_count'    => 10
    ];
    public function consumeMessage($data, AMQPMessage $message): string
    {
        try {
            //这里判断消息的类型
            $result = SearchService::instance()->SyncMultiDoc($data,SearchService::T_B);
            if($result['code'] == Normal::SUC){
                return Result::ACK;
            }else{
                 //失败,重回队列
                 $contents = json_encode($result,JSON_UNESCAPED_UNICODE);
                 MonitorService::instance()->sendMsg($contents);
                 sleep(3);
                 return Result::REQUEUE;
            }
        } catch ( \Throwable $t ) {
            $error = [
                'error'         => $t->getMessage(),
                'errorFile'     => $t->getFile(),
                'errorLine'     => $t->getLine(),
            ];
            $contents = json_encode($error,JSON_UNESCAPED_UNICODE);
            MonitorService::instance()->sendMsg($contents);
            sleep(10);//休眠3秒之后，重回队列
            return Result::REQUEUE;
        }
    }
    
    /**
     * 设置是否自启动
     */
    public function isEnable() : bool
    {
        $isDisAable = env('AMQP_QQC_COMMODITY_ES_MESSAGE_CONSUMER_DISABLE');
        return $isDisAable ? false : true ;
    }
}